//
//  MyCoreHandle.m
//  RedManStock
//
//  Created by lanou3g on 15/8/5.
//  Copyright (c) 2015年 lanou3g. All rights reserved.
//

#import "MyCoreHandle.h"
#import "MyCoreEntrust.h"
#import "MyCorePosition.h"
#import "AppDelegate.h"
#import "User.h"
#import "SimpleStock.h"
#import "MyHandle.h"
static MyCoreHandle *myCoreHandleInstance=nil;
@implementation MyCoreHandle

+(MyCoreHandle *)shareHandle{
    if (myCoreHandleInstance==nil) {
        myCoreHandleInstance=[[MyCoreHandle alloc]init];
    }
    return myCoreHandleInstance;
}

- (NSManagedObjectContext *)mContext{
    if (_mContext!=nil) {
        return _mContext;
    }
    AppDelegate *myAppDelegate=(AppDelegate *)[UIApplication sharedApplication].delegate;
    _mContext=myAppDelegate.managedObjectContext;
    return _mContext;
}

//position创建方法
- (MyCorePosition *)onePosition{
    NSEntityDescription *positionED=[NSEntityDescription entityForName:@"MyCorePosition" inManagedObjectContext:self.mContext];
    MyCorePosition *newPosition=[[MyCorePosition alloc]initWithEntity:positionED insertIntoManagedObjectContext:self.mContext];
    return newPosition;
}

//entrust创建方法
- (MyCoreEntrust *)oneEntrust{
    NSEntityDescription *entrustED=[NSEntityDescription entityForName:@"MyCoreEntrust" inManagedObjectContext:self.mContext];
    MyCoreEntrust *newEntrust=[[MyCoreEntrust alloc]initWithEntity:entrustED insertIntoManagedObjectContext:self.mContext];
    return newEntrust;
}



- (void)addMyPosition:(SimpleStock *)stock{
    //先查询
    MyCorePosition *position=(MyCorePosition *)[self selectPositionWithCode:stock.code];
    
    //如果不存在就插入
    if (!position) {
        NSLog(@"insert");
        [self insertMyPosition:stock];
        
    }
    //存在就更新
    else{
        NSLog(@"update");
        [self updateMyPosition:stock];
        
    }
}

/*说明
 *1.position中，存入股票名称，股票代码，成本价，持仓数量，可卖数量，可卖的时间，最新市值，和盈亏，现价
 *2.simpleStock中会当参数传入的时候，需要设置entrustPrice(更新现价的时候需要传0),volume(如果光是更新现价的数据，则需要传0),which(冻结资金，交易金额)
 *
 */


#pragma mark - MyPosition -
//增: 新成交的委托; 之前position的name，code以及nowPrice都知道
- (void)insertMyPosition:(SimpleStock *)stock{
    //第一次进来，肯定是委托成功后进来的，将nowPrice当做成交价
    //最初 现价，和持仓数量是已知的，可买数量为0股
    float a=[stock.entrustPrice floatValue];
    float b=[stock.volume floatValue];
    float c=a*1.00118;
    MyCorePosition *position=[self onePosition];
    position.stockName=stock.name;
    position.stockCode=stock.code;
    position.nowPrice=stock.entrustPrice;
    position.volume=stock.volume;
    position.costPrice=[NSString stringWithFormat:@"%.2f",c];
    position.updownRate=[NSString stringWithFormat:@"%.2f%%",(a-c)/c*100];
    position.availableVolume=@"0";
    position.nowTotalPrice=[NSString stringWithFormat:@"%.2f",a*b];
    //只需获取一个day的值存起来就可以，到时判断两个day是否相等
    NSDateComponents *time=[MyHandle getNowDetailDate];
    position.canNotSellDate=[NSString stringWithFormat:@"%lu",time.day];
    //保存
    NSError *saveError=nil;
    [self.mContext save:&saveError];
    if (saveError) {
        NSLog(@"%s__%d__ | Error = %@",__FUNCTION__,__LINE__,saveError);
    }
}
//删一个
- (void)deleteMyPosition:(MyCorePosition *)position{
    [self.mContext deleteObject:position];
    NSError *saveError=nil;
    [self.mContext save:&saveError];
    if (saveError) {
        NSLog(@"%s__%d__ | Error = %@",__FUNCTION__,__LINE__,saveError);
    }
}


//改,每次请求好数据，或者委托成功后修改，主要计算成本价，持仓数量; 但取消委托后也要计算啊啊啊
- (void)updateMyPosition:(SimpleStock *)stock{
    //分成卖出的和买入的
    float a=[stock.entrustPrice floatValue];
    float b=[stock.volume floatValue];
    MyCorePosition *position=[self selectPositionWithCode:stock.code];
    //之前花费的总金额
    float c=[position.volume floatValue]*[position.costPrice floatValue];
    //买入,或者获取到nowPrice更新的状态，如果是更新，则stock的volume应该给@"0"
    if ([stock.which isEqualToString:@"冻结资金"]) {
        position.volume=[NSString stringWithFormat:@"%.0f",b+[position.volume floatValue]];
        
        position.nowPrice=stock.nowPrice;
        position.nowTotalPrice=[NSString stringWithFormat:@"%.2f",[position.volume floatValue]*[position.nowPrice floatValue]];
        
        position.costPrice=[NSString stringWithFormat:@"%.2f",(c+a*b*1.00118)/[position.volume floatValue]];
        position.updownRate=[NSString stringWithFormat:@"%.2f%%",([position.nowPrice floatValue]-[position.costPrice floatValue])/[position.costPrice floatValue]*100];
        NSDateComponents *time=[MyHandle getNowDetailDate];
        NSInteger d=time.day;
        if ([position.canNotSellDate integerValue]==d) {
//            position.availableVolume=[NSString stringWithFormat:@"%.0f",[position.availableVolume floatValue]+[stock.volume floatValue]];
        }
        else{
            position.canNotSellDate=[NSString stringWithFormat:@"%lu",d];
            position.availableVolume=[NSString stringWithFormat:@"%.0f",[position.availableVolume floatValue]+[stock.volume floatValue]];
        }
    }
    //卖出
    else{
        position.volume=[NSString stringWithFormat:@"%.0f",[position.volume floatValue]-b];
        position.nowPrice=stock.nowPrice;
        position.nowTotalPrice=[NSString stringWithFormat:@"%.2f",[position.volume floatValue]*[position.nowPrice floatValue]];
        position.costPrice=[NSString stringWithFormat:@"%.2f",(c-a*b*(1-0.00118))/[position.volume floatValue]];
        position.updownRate=[NSString stringWithFormat:@"%.2f%%",([position.nowPrice floatValue]-[position.costPrice floatValue])/[position.costPrice floatValue]*100];
        position.availableVolume=[NSString stringWithFormat:@"%.0f",[position.availableVolume floatValue]-[stock.volume floatValue]];
    }
    NSError *saveError=nil;
    [self.mContext save:&saveError];
    if (saveError) {
        NSLog(@"%s__%d__ | Error = %@",__FUNCTION__,__LINE__,saveError);
    }
}

//查某个
- (MyCorePosition *)selectPositionWithCode:(NSString *)code{
    NSFetchRequest *fetchRequest=[NSFetchRequest fetchRequestWithEntityName:@"MyCorePosition"];
    NSPredicate *predicate=[NSPredicate predicateWithFormat:@"stockCode==%@",code];
    fetchRequest.predicate=predicate;
    NSSortDescriptor *sortD=[NSSortDescriptor sortDescriptorWithKey:@"canNotSellDate" ascending:YES];
    fetchRequest.sortDescriptors=@[sortD];
    NSError *error=nil;
    NSArray *array=[self.mContext executeFetchRequest:fetchRequest error:&error];
    if (error) {
        NSLog(@"%s__%d__ | Error = %@",__FUNCTION__,__LINE__,error);
#warning 这里不存在的话并不会走到error中，而是
        return nil;
    }
    if (array.count>0) {
        return array[0];
    }
    else return nil;
}

//查全部
- (NSArray *)selectAllCorePosition{
    NSFetchRequest *fetchRequest=[NSFetchRequest fetchRequestWithEntityName:@"MyCorePosition"];
    NSSortDescriptor *sortD=[NSSortDescriptor sortDescriptorWithKey:@"canNotSellDate" ascending:YES];
    fetchRequest.sortDescriptors=@[sortD];
    NSError *error=nil;
    NSArray *array=[self.mContext executeFetchRequest:fetchRequest error:&error];
    if (error) {
        NSLog(@"%s__%d__ | Error = %@",__FUNCTION__,__LINE__,error);
        return [NSArray array];
    }
    return array;
}

#pragma mark - MyEntrust -

//增
- (void)addMyCoreEntrust:(SimpleStock *)stock{
    
    MyCoreEntrust *entrust=[self oneEntrust];
    entrust.stockCode=stock.code;
    entrust.stockName=stock.name;
    entrust.which=stock.which;
    entrust.entrustPrice=stock.entrustPrice;
    entrust.volume=stock.volume;
    NSDateComponents *nowTime=[MyHandle getNowDetailDate];
    entrust.entrustDate=[NSString stringWithFormat:@"%lu月%lu日 %lu:%lu:%lu",nowTime.month,nowTime.day,nowTime.hour,nowTime.minute,nowTime.second];
    entrust.tradePrice=[NSString stringWithFormat:@"%.2f",[entrust.volume floatValue]*[entrust.entrustPrice floatValue]];
    NSError *saveError=nil;
    [self.mContext save:&saveError];
    if (saveError) {
        NSLog(@"%s__%d__ | Error = %@",__FUNCTION__,__LINE__,saveError);
    }
    
}

//删
- (void)deleteMyEntrust:(NSString *)entrustDate{
    NSLog(@"entrustData=%@",entrustDate);
    MyCoreEntrust *entrust=[self selectEntrustWithDate:entrustDate];
    NSLog(@"entrust=%@",entrust);
    [self.mContext deleteObject:entrust];
    NSError *saveError=nil;
    [self.mContext save:&saveError];
    if (saveError) {
        NSLog(@"%s__%d__ | Error = %@",__FUNCTION__,__LINE__,saveError);
    }
}

//删除全部
- (void)deleteAllMyEntrust{
    NSArray *array=[self selectAllEntrust];
    for (MyCoreEntrust *entrust in array) {
        [self.mContext deleteObject:entrust];
    }
    NSError *saveError=nil;
    [self.mContext save:&saveError];
    if (saveError) {
        NSLog(@"%s__%d__ | Error = %@",__FUNCTION__,__LINE__,saveError);
    }
}

//查一个，根据委托时间
- (MyCoreEntrust *)selectEntrustWithDate:(NSString *)entrustDate{
    NSFetchRequest *fetchRequest=[NSFetchRequest fetchRequestWithEntityName:@"MyCoreEntrust"];
    NSSortDescriptor *sortD=[NSSortDescriptor sortDescriptorWithKey:@"entrustDate" ascending:YES];
    fetchRequest.sortDescriptors=@[sortD];
    NSError *error=nil;
    NSArray *array=[self.mContext executeFetchRequest:fetchRequest error:&error];
    if (error) {
        NSLog(@"%s__%d__ | Error = %@",__FUNCTION__,__LINE__,error);
        return nil;
    }
    if (array.count>0) {
        return array[0];
    }
    else return nil;
}

//查全部
-(NSArray *)selectAllEntrust{
    NSFetchRequest *fetchRequest=[NSFetchRequest fetchRequestWithEntityName:@"MyCoreEntrust"];
    NSSortDescriptor *sortD=[NSSortDescriptor sortDescriptorWithKey:@"entrustDate" ascending:YES];
    fetchRequest.sortDescriptors=@[sortD];
    NSError *error=nil;
    NSArray *array=[self.mContext executeFetchRequest:fetchRequest error:&error];
    if (error) {
        NSLog(@"%s__%d__ | Error = %@",__FUNCTION__,__LINE__,error);
        return [NSArray array];
    }
    return array;
}


@end
